package cn.bone.elasticsearch.web;

import cn.bone.elasticsearch.bean.News;
import cn.bone.elasticsearch.dao.NewsDao;
import io.searchbox.client.JestClient;
import io.searchbox.core.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * Created by MD-01 on 2017/3/21.
 */
@RestController
@RequestMapping("/search")
public class SearchController {

    @Resource
    private NewsDao newsDao;

    @Resource
    private JestClient jestClient;

    private Logger logger = LoggerFactory.getLogger("搜索");

    @RequestMapping("/test")
    public void test(){
        List<News> list = newsDao.queryList(100);
        for(News news : list){
            System.out.println(news.getTitle());
        }
    }

    @RequestMapping("/index")
    public boolean index(){

        boolean result = false;

        /*JestClientFactory factory = new JestClientFactory();
        factory.setHttpClientConfig(new HttpClientConfig
                .Builder("http://localhost:9200")
                .gson(new GsonBuilder().setDateFormat("yyyy-MM-dd'T'hh:mm:ss").create())
                .connTimeout(1500)
                .readTimeout(3000)
                .multiThreaded(true)
                .build());
        JestClient client = factory.getObject();*/

        Bulk.Builder bulk = new Bulk.Builder()
                .defaultIndex("superbone")
                .defaultType("news");
        List<News> list = newsDao.queryList(100);
        for(News news : list){
            System.out.println(news.getTitle());
            Index index = new Index.Builder(news).build();
            bulk.addAction(index);
        }
        try {
            BulkResult bulkResult = jestClient.execute(bulk.build());
            if(bulkResult.isSucceeded()){
                System.out.println("存储索引成功");
            }else{
                System.out.println(bulkResult.getErrorMessage());
                List<BulkResult.BulkResultItem> items = bulkResult.getItems();
                items.forEach(item->{
                    System.out.println(item.id+":"+item.error);
                });
            }
            result = bulkResult.isSucceeded();
            System.out.println(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/query")
    public void query(String keyword,Integer from,Integer size){
        if(from==null){
            from = 0;
        }
        if(size==null){
            size = 10;
        }

        /*
            将查询语句的字符串传入Search.Builder中
            {
                "query":{
                    "multi_match":{
                        "query":"阳新",
                        "fields": ["title","content"]
                    }
                },
                "from": 0,
                "size": 20
            }
        */
        String query = "{\"query\":{" +
                                    "\"multi_match\":{" +
                                    "\"query\":\""+keyword+"\"," +
                                    "\"fields\":[\"title\",\"content\"]" +
                                    "}" +
                                "}," +
                         "\"from\":"+from+","+
                         "\"size\":"+size+
                        "}";
        Search search = new Search.Builder(query)
                .addIndex("superbone")
                .addType("news")
                .build();
        try {
            SearchResult searchResult = jestClient.execute(search);
            if(searchResult.isSucceeded()){
                Integer total = searchResult.getTotal();
                logger.info("查询到:"+total+"条记录");
                List<SearchResult.Hit<News, Void>> hits = searchResult.getHits(News.class);
                logger.info(String.valueOf(hits.size()));
                hits.forEach(hit -> {
                    String id = hit.id;
                    News news = hit.source;
                    logger.info("id:"+id);
                    logger.info("title:"+news.getTitle());
                });
            }else{
                logger.info("查询不成功:"+searchResult.getErrorMessage());
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/delete")
    public boolean delete(String id){

        boolean result = false;
        Delete delete = new Delete.Builder("75776")
                .index("superbone")
                .type("news")
                .build();
        try {
            DocumentResult deleteResult = jestClient.execute(delete);
            result = deleteResult.isSucceeded();
            if(deleteResult.isSucceeded()){
                logger.info("删除成功:"+deleteResult.getId());
            }else{
                logger.info("删除失败:"+deleteResult.getId());
                logger.info(deleteResult.getErrorMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
}
